package com.ititer.web.controller;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;

import com.ititer.bean.AccountBean;
import com.ititer.enums.AccountStatus;
import com.ititer.enums.DefaultValues;
import com.ititer.service.AccountService;
import com.ititer.util.RandomPasswordGenerator;
import com.ititer.web.abs.AbstractController;

@Resource
public class Register extends AbstractController {
	final Logger logger = LoggerFactory.getLogger(Register.class);

	@Autowired
	private AccountService accountService;

	@Get
	@Path({ "/register" })
	public void form() {
		setPageTitle("Welcome to join Ititer ~");
	}

	@Post
	@Path({ "/register" })
	public AccountBean save(final AccountBean account) {
		setPageTitle("Registering ~");
		logger.debug("Receiving register for {} .", account.getEmail());
		account.setIp(getIp());
		account.setReferer(getReferer());
		account.setPasswd(RandomPasswordGenerator.gen());
		account.setCreateTime(new Date());
		account.setStatus(AccountStatus.Registering.name());
		account.setAvatar(DefaultValues.DefaultAvatar.getValue());

		validate(account).onErrorUsePageOf(Register.class).form();

		boolean exist = accountService.isEmailExist(account.getEmail());
		if (exist) {
			setErrorMessage("account.already.exists", account.getEmail());
			controllerResult.forwardTo(Register.class).form();
			return null;
		}

		boolean success = accountService.register(account);
		if (success) {
			return account;
		} else {
			controllerResult.redirectTo(Error.class).info();
			return null;
		}
	}
}
